package com.millstein.controller;

import com.google.code.kaptcha.Producer;
import com.millstein.enums.BizCodeEnum;
import com.millstein.enums.user.SendCodeEnum;
import com.millstein.service.NotifyService;
import com.millstein.util.CommonUtils;
import com.millstein.util.JsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: tsing
 * @create: 2021-09-10 13:37
 */
@Api("通知控制器")
@RestController
@RequestMapping("/api/notify/v1")
@Slf4j
public class NotifyController {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private NotifyService notifyService;

    /**
     * 验证码的有效时间
     */
    private static final long CAPTCHA_CODE_EXPIRED = 10 * 60 * 1000;

    @ApiOperation("获取图形验证码")
    @GetMapping("/captcha")
    public void getCaptcha(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response) {
        // 生成验证码
        String captchaText = captchaProducer.createText();
        log.info("生成的验证码为：{}", captchaText);

        // 将验证码存到redis中（因为有可能会集群部署）
        redisTemplate.opsForValue().set(this.getRedisKeyForCaptcha(request), captchaText,
                CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);

        // 输出验证码图片
        BufferedImage image = captchaProducer.createImage(captchaText);
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (Exception e) {
            log.error("生成验证码时发生异常，原因是：{}", e.getMessage(), e);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("关闭输出流时发生异常，原因是：{}", e.getMessage(), e);
            }
        }
    }

    /**
     * 获取存储验证码的redis key
     * 因为在获取验证码时，得不到用户的任何信息，那么只能通过ip地址和User-Agent来分辨
     * 然而User-Agent的长度过长，所以我们采用将这个值进行md5加密后作为redis中的key
     * @param request 请求对象
     * @return
     */
    private String getRedisKeyForCaptcha(HttpServletRequest request) {
        String ip = CommonUtils.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        return "user-service:captcha:" + CommonUtils.MD5(ip + userAgent);
    }

    /**
     * 发送邮箱验证码
     * @param to 收件人
     * @param captcha 图形验证码
     * @return
     */
    @ApiOperation("发送邮箱验证码")
    @GetMapping("send_code")
    public JsonData sendRegisterCode(@RequestParam("to") String to, @RequestParam("captcha") String captcha,
                                     HttpServletRequest request) {
        String key = getRedisKeyForCaptcha(request);
        Object captchaCode = redisTemplate.opsForValue().get(key);

        if (captchaCode != null && captcha.equalsIgnoreCase((String) captchaCode)) {
            // 成功
            // 清空redis key
            redisTemplate.delete(key);
            notifyService.sendCode(SendCodeEnum.USER_REGISTER, to);
            return JsonData.buildSuccess();
        } else {
            // 失败
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }
    }
}
